<template>
    <div class="store">
        <Tabs type="card"  v-model='currentTab' closable :animated="false">
            <TabPane label="门店管理" :closable='false'  v-if='!spinShow'>
                <div class="yd-header margin-top-8">
                    <span>门店</span>
                    <Button type="primary" class="btn-in-top-large" @click="popup(1)" v-pmis="38">添加门店</Button>
                </div>

                <div @keydown.enter="search()" class='margin-top-20'>
                    <Row :gutter='8'>
                        <Col span='24'>
                            <Input placeholder='关键字：门店名' icon="ios-search-strong" @on-enter="search" @on-click="search" v-model='listQuery.keyword'></Input>
                        </Col>
                    </Row>
                </div>

                <div v-if="!list || !list.length" class="no-data">
                    暂无匹配的数据
                </div>

                <Row v-for='(item , index) in list' :key="index" class="store-item margin-top-10 bill-account-info">
                    <Col span='5' class='store-item-left'>
                        <Row type="flex" justify="center" align="middle" class="code-row-bg" style='height:100%;padding:0 20px;'>
                            <span style='font-size:18px'>{{item.name}}</span>
                        </Row>
                    </Col>
                    <Col span='8' class='store-item-center' style="height: 100%;border-right: 1px dashed #ccc;">
                        
                        <Row>
                            <Col span="24">
                                <h3>银联收款账户信息</h3>
                                <Row :gutter='16'>
                                    <Col span='24' class='margin-top-20'>
                                        <strong>当前收款账户：</strong>
                                        {{item.status | statusFilter}}
                                    </Col>
                                </Row>
                                <Row :gutter='16'>
                                    <Col span='24' class='margin-top-10'>
                                        <strong>银行户名：</strong>
                                        {{item.customerName}}
                                    </Col>
                                </Row>
                                <Row :gutter='16'>
                                    <Col span='24' class='margin-top-10'>
                                        <strong>银行账户：</strong>
                                        {{item.cardNo}}
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                    </Col>
                    <Col span='8' class='store-item-center' style="height: 100%;border-right: 1px dashed #ccc;">
                        
                        <Row>
                            <Col span="24">
                                <h3>支付宝收款账户信息</h3>
                                <Row :gutter='16'>
                                    <Col span='24' class='margin-top-20'>
                                        <strong>当前收款账户：</strong>
                                        {{item.alipayStatus | statusFilter}}
                                    </Col>
                                </Row>
                                <Row :gutter='16'>
                                    <Col span='24' class='margin-top-10'>
                                        <strong>银行户名：</strong>
                                        {{item.alipayCustomerName}}
                                    </Col>
                                </Row>
                                <Row :gutter='16'>
                                    <Col span='24' class='margin-top-10'>
                                        <strong>银行账户：</strong>
                                        {{item.alipayCardNo}}
                                    </Col>
                                </Row>
                                <Row :gutter='16'>
                                    <Col span='24' class='margin-top-10'>
                                        <strong>身份证号：</strong>
                                        {{item.alipayIdcard}}
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                    </Col>
                    <!-- <Col span='8' class='store-item-center'>
                        <h3 class="margin-bottom-20">
                            缴费账户信息
                            <i-button
                                size="small"
                                class="bill-btn"
                                @click="handleFetchInfo(index, item.id)"
                                v-show="!item.hideBtn && item.agency_pay && !item.audit">获取信息</i-button>
                            <i-button
                                size="small"
                                v-if="!item.agency_pay && !item.isAuditing"
                                @click="handleAli(item)">开通</i-button>
                        </h3>
                        <div class="margin-bottom-10">当前状态: {{item.agency_pay ? '开通' : item.isAuditing ? '审核中' : '未开通'}}</div>
                        <span v-show="item.loading">加载中...</span>
                        <div v-if="item.audit">
                            <div class="margin-bottom-10">支付宝账号：{{item.audit.account}}</div>
                            <div class="margin-bottom-10">APPID：{{item.audit.appid}}</div>
                        </div>
                    </Col> -->
                    <Col span='3' class='store-item-right'>
                        <Button type='primary' class='margin-left-10' @click='popup(2,item.id,item.name)' v-pmis="38">编辑名称</Button>
                        <Button type='primary' class='margin-left-10' @click="editBankCard(item)" v-pmis="34" v-if="isClient">编辑银联收款账户</Button>
                        <Button type='primary' class='margin-left-10' @click="editAlipayCard(item)" v-pmis="34" v-if="isClient">编辑支付宝收款账户</Button>
                        <Button type='primary' class='margin-left-10'
                        v-pmis="38"
                        @click='popup(3,item.id)' v-if='!item.branch_account || !item.branch_account.cash_amount'>
                            删除门店
                        </Button>

                        <Button type='primary' class='margin-left-10'
                        v-pmis="38"
                        @click='delete_warn = true' v-if='item.branch_account && item.branch_account.cash_amount && item.branch_account.cash_amount !== 0'>
                            删除门店
                        </Button>
                    </Col>
                </Row>

                <Modal v-model="alipayAccoundModal"  :mask-closable=false :width="500">
                    <h3 slot="header" style="color:#5B5B5B;font-size:18px;">选择支付宝收款账户</h3>
                    
                    <Form
                        style="padding: 0 20px"
                        ref="bank"
                        :model="alipayParams"
                        label-position="right"
                        :label-width="150"
                        :show-message="false">

                        <FormItem label="当前收款账户">
                            <Select v-model="alipayParams.account" @on-change="changeAlipayAccountType">
                                <Option :value="1">总部账户</Option>
                                <Option :value="2" :disabled="alipayParams.isDisable">门店独立账户</Option>
                            </Select>
                        </FormItem>

                        <!-- 银行户名 -->
                        <FormItem label="银行户名">
                            {{alipayParams.alipayCustomerName}}
                        </FormItem>

                        <!-- 银行账号 -->
                        <FormItem label="银行账号">
                             {{alipayParams.alipayCardNo}}
                        </FormItem>

                         <!-- 持卡人身份证号 -->
                        <FormItem label="身份证号">
                             {{alipayParams.alipayIdcard}}
                        </FormItem>
                    </Form>

                    <div slot="footer">
                        <Button type="ghost"  class='yd-button' @click="prevAliClick" v-if="alipayParams.prevName !== ''">{{alipayParams.prevName}}</Button>
                        <Button type="primary" v-if="alipayParams.nextName !== ''" @click="nextAliClick">{{alipayParams.nextName}}</Button>
                    </div>
                    
                </Modal>

                <!-- 分店账号 -->
                <Modal v-model="accoundModal"  :mask-closable=false :width="500">
                    <h3 slot="header" style="color:#5B5B5B;font-size:18px;">选择银联收款账户</h3>

                    <Form
                        style="padding: 0 20px"
                        ref="bank"
                        :model="bankParams"
                        label-position="right"
                        :label-width="150"
                        :show-message="false">

                        <FormItem label="当前收款账户">
                            <Select v-model="bankParams.account" @on-change="changeAccountType">
                                <Option :value="1">总部账户</Option>
                                <Option :value="2" :disabled="bankParams.isDisable">门店独立账户</Option>
                            </Select>
                        </FormItem>

                        <!-- 银行户名 -->
                        <FormItem label="银行户名">
                            {{bankParams.customerName}}
                        </FormItem>

                        <!-- 银行账号 -->
                        <FormItem label="银行账号">
                             {{bankParams.cardNo}}
                        </FormItem>

                        <FormItem label="提示" v-if="bankParams.status == 1">
                             {{bankParams.tip}}
                        </FormItem>

                        <FormItem label="提示" v-if="bankParams.status == 2 && bankParams.account == 2">
                             尊敬的客户：因银联接口问题，暂无法申请独立账户，如需门店独立核算，请申请支付宝分账
                        </FormItem>
                    </Form>

                    <div slot="footer">
                        <Button type="ghost"  class='yd-button' @click="prevClick" v-if="bankParams.prevName !== ''">{{bankParams.prevName}}</Button>
                        <Button type="primary" v-if="bankParams.nextName !== ''" @click="nextClick">{{bankParams.nextName}}</Button>
                    </div>
                </Modal>
                
                 <!-- 申请支付宝分账前的信息确认弹窗 -->
                <tooltip-modal 
                    v-model="showTipModal" 
                    @finish="openAlipayModal"
                />

                <!-- 提交数据 -->
                <enable-recharge :show.sync="enableRecharge.formVisible" :dataParams="params" @confirm="goToMsm" :accountName="accountName" ></enable-recharge>

                <!-- 短信校验成功给出提示 -->
                <recharge-introduction  
                    :client-phone="clientPhone"
                    :show.sync="enableRecharge.introductionVisible"
                    :paramsData="paramsData"
                    :isChangeAccountType="isChangeAccountType"
                    @confirm="confirm"
                    @changeAccountType="fixAccountType"></recharge-introduction>

                <!-- 短信校验成功给出提示 -->
                <recharge-introduction  
                    :client-phone="clientPhone"
                    :show.sync="alipaySmsShow"
                    :platform_id="2"
                    :paramsData="{}"
                    @Alipay="changeAliAccount"></recharge-introduction>

                <Modal v-model="add_model" :closable='false' :mask-closable=false :width="500">
                    <h3 slot="header" style="color:#5B5B5B;font-size:18px;">添加门店</h3>
                    <div class='text-center' style='height:80px;padding-top:22px;'>
                        <Input v-model="add_branch_name" :maxlength="12" placeholder="门店名称" style='width:90%' key='add'>
                        </Input>
                    </div>
                    <div slot="footer">
                        <Button type="ghost" @click="cancelPass(1)" class='yd-button'>取消</Button>
                        <Button type="primary" @click="ok()">保存</Button>
                    </div>
                </Modal>

                <Modal v-model="edit_model" :closable='false' :mask-closable=false :width="500">
                    <h3 slot="header" style="color:#5B5B5B;font-size:18px;">编辑门店</h3>
                    <div class='text-center' style='height:80px;padding-top:22px;'>
                        <Input v-model="edit_branch_name" placeholder="修改门店名称" style='width:90%' key='edit'></Input>
                    </div>
                    <div slot="footer">
                        <Button type="text" @click="cancelPass(2)">取消</Button>
                        <Button type="primary" @click="sureUpdate()">保存</Button>
                    </div>
                </Modal>

                <Modal v-model="delete_model" :closable='false' :mask-closable=false :width="500">
                    <h3 slot='header' style="color:#5B5B5B;font-size:18px;">删除门店</h3>
                    <div class="text-center" style='height:80px;padding-top:30px;'>请确保该门店下无房源及员工，否则将删除失败</div>
                    <div slot="footer">
                        <Button type="ghost" @click="cancelPass(3)" class='yd-button'>取消</Button>
                        <Button type="primary"  @click="sureDelete()">确定</Button>
                    </div>
                </Modal>

                <Modal v-model="delete_warn" :closable='false' :mask-closable=false :width="500">
                    <h3 slot='header' style="color:#5B5B5B;font-size:18px;">删除门店提醒</h3>
                    <div class="text-center" style='height:80px;padding-top:30px;'>
                        当前门店电费余额不为零，请提现完成后再进行删除</div>
                    <div slot="footer">
                        <Button type="ghost" @click="delete_warn = false" class='yd-button'>取消</Button>
                        <Button type="primary"  @click="delete_warn = false">确定</Button>
                    </div>
                </Modal>
                <Page :total="total" :page-size="listQuery.limit" show-elevator show-total style="text-align:center" class='margin-top-10' @on-change='getList'></Page>
            </TabPane>
        </Tabs>

        <alipay-recharge :show.sync="alipayRechargeModal" :dataParams="alipayData" :status="alipayEnableStatus" @refresh="alipay_refresh" :branchId="branchId"></alipay-recharge>
        <Spin size="large" fix v-if="spinShow"></Spin>
    </div>
</template>

<script>
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import captcha from '@/views/captcha'
import dataCenter from '@/libs/dataCenter'
import validate from '@/libs/validate'
import rechargeIntroduction from '@/views/fund/components/recharge-introduction'
import enableRecharge from '@/views/fund/components/enable-recharge'
import tooltipModal from '@/views/fund/components/tooltip-modal.vue'
import alipayRecharge from '@/views/fund/components/alipay-recharge'

export default {
  name: 'stores_index',
  created () {
    this.getList() // 获取列表信息
    this.fetchEnableRechargeStatus()
    this.getClientPhone() // 获取商户的手机号
    // this.fetchClientAliInfo();
  },
  data () {
    return {
      showTipModal: false, // 是否打开提示弹窗
      alipaySmsShow: false, // 阿里短信确认是否展示
      branchId: -1,
      alipayEnableStatus: null, // 分店是否开通
      alipayData: {}, // 参数对象
      alipayRechargeModal: false, // 支付宝申请弹窗
      alipayParams: {},
      alipayAccoundModal: false, // 支付宝账户切换
      accountName: '',
      parentId: -1, // 上一条记录的id
      isChangeAccountType: false,
      paramsData: {}, // 提交传参数
      accoundModal: false, // 选择收款账户
      enableRecharge: {
        introductionVisible: false, // 介绍弹窗是否打开
        formVisible: false // 绑定资料弹窗是否打开
      },
      params: {}, // 获取params中的参数
      bankParams: {
        account: 1
      },
      canOpenAli: false,
      currentTab: 0,
      list: [],
      chargeStore: [],
      total: null,
      loading: true,
      spinShow: true,
      reset: false,
      listQuery: {
        offset: 0,
        limit: 10,
        keyword: ''
      },

      isWaitingForSMS: false,
      second: 60,
      timer: '',
      clientPhone: '',
      add_branch_name: '',
      edit_branch_name: '',
      id: '',
      add_model: false,
      edit_model: false,
      edit_bank_model: false,
      delete_model: false,
      delete_warn: false,

      accountType: [{ type: 1, label: '银行卡' }, { type: 2, label: '微信' }, { type: 3, label: '支付宝' }],

      addAccount: false,
      tip_model: false,

      formItem: {
        phone_no: '',
        customer_name: '',
        bank_name: '',
        bank_province: '',
        bank_city: '',
        card_no: '',
        id_card: '',
        msg_code: '',
        is_company: 0,
        captcha_code: '',
        branch_id: '',
        cash_type: ''
      },
      provinces: [],
      countrys: [],
      banks: [],

      ruleValidate2: {
        customer_name: [
          {
            required: true,
            message: '请输入正确的银行开户名',
            trigger: 'blur',
            validator: validate.validChinese
          }
        ],
        card_no: [
          {
            required: true,
            message: '请输入正确的银行卡号',
            trigger: 'blur'
          },
          { validator: validate.validBankCard }
        ],
        id_card: [
          {
            required: true,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          },
          { validator: validate.validIDCard }
        ],
        is_company: [
          {
            required: true
          }
        ],
        cash_type: [
          {
            required: true
          }
        ],
        phone_no: [
          {
            required: true,
            message: '请输入正确的手机号',
            trigger: 'change'
          },
          { validator: validate.validPhone }
        ],
        msg_code: [
          {
            required: true,
            message: '请输入短信验证码',
            trigger: 'blur'
          }
        ],
        captcha_code: [
          {
            required: true,
            message: '请进行人机验证',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  methods: {
    /**
        *
        */
    changeAliAccount (msmCode) {
      const { id, account, alipayAccountId, alipayRouteAccountId } = this.alipayParams
      const params = {
        branch_id: id,
        platform_id: account === 1 ? alipayAccountId : alipayRouteAccountId,
        msg_code: msmCode
      }
      http.request(this, api.pay_accounts_change, null, params, (res, error) => {
        if (!error && res) {
          this.alipaySmsShow = false
          this.getList()
        }
      })
    },

    /**
        * 申请完成
        */
    alipay_refresh () {
      this.getList()
    },
    prevAliClick () {
      const { prevName } = this.alipayParams

      if (prevName === '申请开通') {
        this.alipayData = {}
        this.showTipModal = true
      } else if (prevName === '变更收款账户') {
        this.showTipModal = true
      }
      this.alipayAccoundModal = false
    },

    openAlipayModal () {
      this.branchId = this.alipayParams.id
      this.alipayRechargeModal = true
    },

    nextAliClick () {
      const { nextName } = this.alipayParams
      if (nextName === '确认切换') {
        this.alipayAccoundModal = false
        this.alipaySmsShow = true
      }
    },

    changeAlipayAccountType (type) {
      const { alipayStatus } = this.alipayParams

      // console.log('alipayStatus', alipayStatus);
      if (alipayStatus === 2) {
        // 当总部开通门店未开通情况下
        if (type === 2) {
          // 由总部切换为门店的时候
          // console.log('enter', 5);
          this.setButtonName(5, true)
        } else {
          // 由分店切换为总部
          // console.log('enter', 2);
          this.setButtonName(2, true)
        }
      } else if (alipayStatus === 3 || alipayStatus === 4) {
        // 当总部和门店都已经开通
        if (type === 1) {
          // 由分店切换为总部
          // console.log('enter', 4);
          this.setButtonName(4, true)
        } else {
          // 由总部切换为分店
          // console.log('enter', 3);
          this.setButtonName(3, true)
        }
      }
      // console.log(this.alipayParams.prevName, '-', this.alipayParams.nextName, '-');

      const params = type === 1 ? null : { branch_id: this.alipayParams.id }

      http.request(this, api.alipay_register_query, null, params, (res, error) => {
        if (res) {
          const { operation_stage } = res

          if (typeof operation_stage === 'object') {
            this.setAliBankData('未设置')
          } else {
            const { data: { principal_person, bank_card_no, principal_cert_no } } = res
            this.setAliBankData(principal_person, bank_card_no, principal_cert_no)

            if (params.branch_id && operation_stage !== 2) {
              this.alipayEnableStatus = operation_stage + 1
              this.alipayData = res.data
            }
          }
        }
      })
    },

    setAliBankData (name, no, id) {
      if (!no) {
        no = name
        id = name
      }

      this.$set(this.alipayParams, 'alipayCustomerName', name)
      this.$set(this.alipayParams, 'alipayCardNo', no)
      this.$set(this.alipayParams, 'alipayIdcard', id)
    },

    async fetchEnableRechargeStatus () {
      try {
        const res = await http.req(api.audit_info, null, {
          audit_type: 1
        })
        if (res) {
          const { name } = res
          this.accountName = name
        }
      } catch (err) {
      }
    },
    /**
         * 编辑收款账户弹窗左边按钮
         */
    prevClick () {
      const { prevName } = this.bankParams

      if (prevName === '申请开通') {
        this.openDoorRechart()
      } else if (prevName === '变更收款账户') {
        this.params = {}
        this.getParams()
      } else if (prevName === '变更收款账户') {
      }
      this.accoundModal = false
    },

    async openDoorRechart () {
      try {
        const res = await http.req(api.audit_info, null, {
          audit_type: 1,
          branch_id: this.bankParams.id
        })

        if (res) {
          if (res.audit) {
            const { state } = res.audit
            if (state === 1 || state === 2) {
              this.$Message.error('您已经提交了资料，正在审核中请稍等!')
            } else {
              this.enableRecharge.formVisible = true
            }
          } else {
            this.enableRecharge.formVisible = true
          }
        }
      } catch (err) {
        console.log(err)
      }
    },

    async getParams () {
      try {
        const res = await http.req(api.audit_history, null, {
          audit_type: 1,
          branch_id: this.bankParams.id
        })
        if (res) {
          const { id } = res
          this.parentId = id
          this.params = res
          this.enableRecharge.formVisible = true
        }
      } catch (err) {
        console.log(err)
      }
    },

    /**
         * 编辑收款账户弹窗右边按钮
         */
    nextClick () {
      const { nextName } = this.bankParams

      if (nextName === '确认切换') {
        this.isChangeAccountType = true // 给弹窗标示是切换门店
        this.enableRecharge.introductionVisible = true // 打开短信验证弹窗
      }
      this.accoundModal = false
    },

    /**
         * 修改账户类型
         */
    async fixAccountType (code) {
      const { id, account, clientAccountId, routeAccountId } = this.bankParams
      const params = {
        msg_code: code,
        branch_id: id,
        platform_id: account === 1 ? clientAccountId : routeAccountId
      }
      try {
        const res = await http.req(api.pay_accounts_change, null, params)

        if (res) {
          this.$Message.success('切换成功!')
          this.enableRecharge.introductionVisible = false
          this.getList()
        }
      } catch (err) {
        console.log(err)
      }
    },

    /**
         * 打开短信验证弹窗
         */
    goToMsm (data) {
      if (Object.keys(this.params).length) {
        data.parent_id = this.parentId
        this.params = {}
      }
      data.branch_id = this.bankParams.id // 请求添加branch_id
      this.paramsData = data
      this.enableRecharge.introductionVisible = true
    },

    // 通过审核之后弹出审核中的弹窗
    confirm () {
      // this.enableRecharge.formVisible = true
      this.$Modal.success({
        title: '审核中',
        content:
                    '<p>已成功提交，十个工作日内，商户手机号将收到银联指定收单机构-中投科信的短信。请根据短信提示，完成线上收单流程。如有疑问，请咨询对接商务或客服。</p>'
      })
      // 刷新列表
      this.getList()
    },

    async fetchClientAliInfo () {
      try {
        const res = await http.req(api.audit_info, null, {
          audit_type: 2
        })
        this.canOpenAli = res.audit && res.audit.state === 3
      } catch (err) {
        console.log(err)
      }
    },
    handleAli (item) {
      if (this.canOpenAli) {
        const name = encodeURIComponent(item.name)
        this.$router.push(`/fund/account_information?branchId=${item.id}&branchName=${name}`)
      } else {
        this.$Modal.confirm({
          title: '开通失败',
          content: '请先开通商户电费代缴',
          okText: '前往开通',
          onOk: () => {
            this.$router.push('/fund/account_information')
          }
        })
      }
    },
    async handleFetchInfo (index, branch_id) {
      try {
        this.$set(this.list[index], 'loading', true)
        const res = await http.req(api.agency_pay_info, null, {
          branch_id
        })
        this.$set(this.list[index], 'audit', res.agency_pay_info)
      } catch (err) {
        console.log(err)
      } finally {
        this.$set(this.list[index], 'loading', false)
      }
    },
    resetForm (name) {
      this.$refs[name].resetFields()
      this.formItem.bank_province = ''
      this.formItem.bank_city = ''
      this.formItem.bank_name = ''
    },

    popup (num, id, name) {
      this.id = id
      switch (num) {
        case 1:
          this.add_model = true
          break
        case 2:
          this.edit_model = true
          this.edit_branch_name = name
          break
        case 3:
          this.delete_model = true
          break
      }
    },

    sureDelete () {
      http.request(this, api.branch_del, [this.id], null, (res, err) => {
        if (err || !res) {
          return
        }
        this.delete_model = false
        this.$Message.success('删除门店成功')
        this.getList()
        dataCenter.updateStores(this)
      })
    },

    search () {
      this.getList()
    },
    sureUpdate () {
      http.request(this, api.branch_update, [this.id], { name: this.edit_branch_name }, (res, err) => {
        if (!res || err) {
          return
        }
        dataCenter.updateStores(this)
        this.edit_model = false
        this.edit_branch_name = ''
        this.getList()
      })
    },
    getList (page) {
      if (page) {
        this.listQuery.offset = (page - 1) * this.listQuery.limit
      }
      http.request(this, api.branch_list, null, this.listQuery, (res, err) => {
        if (!res || err) {
          return
        }
        res.list.forEach(item => {
          if (!item.agency_pay && item.audits && item.audits.length) {
            item.isAuditing = item.audits.some(audit => audit.type === 2 && audit.state === 1)
          }
        })
        try {
          this.constructorData(res)
        } catch (error) {
          console.log(error)
        }
        this.spinShow = false
      })
    },

    /**
         * 存在4种情况 根据status的值来判断（1.总部门店都未配置，2.总部配置门店未配置（默认使用总部的配置） 3.使用门店配置 4. 使用总部配置） 3.4 都表示门店有配置
         * 构造相关数据
         * @param { Object } data 返回的商户列表列表
         */
    constructorData (data) {
      const { client_account_info, count, list } = data

      this.total = count

      let clientAccountId

      if (Object.keys(client_account_info).length) {
        const { id } = client_account_info
        clientAccountId = id
      } else {
        clientAccountId = -1
      }

      this.list = list.map(item => {
        item.clientAccountId = clientAccountId

        if (!Object.keys(client_account_info).length) {
          // 如果总部账号未开通的话
          item.status = 1
          item.customerName = '未设置' // 银行户名
          item.cardNo = '未设置' // 银行账户
        } else {
          // 如果总部账号已开通
          const { unionpay_account_info, has_unionpay_account } = item
          const { pay_account: { account_info: { customer_name, card_no } } } = client_account_info

          if (!has_unionpay_account) {
            // 如果该门店账号未开通的,直接取总部的数据
            item.status = 2
            item.customerName = customer_name // 银行户名
            item.cardNo = card_no // 银行账户
          } else {
            // 总部门店都已经开通
            const { is_used } = unionpay_account_info

            if (is_used === 1) {
              // 使用门店配置
              item.status = 3
              item.customerName = unionpay_account_info.pay_account.account_info.customer_name
              item.cardNo = unionpay_account_info.pay_account.account_info.card_no
            } else {
              // 使用总部配置
              item.status = 4
              item.customerName = customer_name // 银行户名
              item.cardNo = card_no // 银行账户
            }
          }
        }
        return item
      })

      // console.log(data);
      this.constructorAlipayData(data)
    },

    /**
         * 存在4种情况 根据status的值来判断（1.总部门店都未配置，2.总部配置门店未配置（默认使用总部的配置） 3.使用门店配置 4. 使用总部配置） 3.4 都表示门店有配置
         * 构造相关数据
         * @param { Object } data 返回的商户列表列表
         */
    constructorAlipayData (data) {
      const { ali_account_info } = data

      let alipayAccountId

      if (Object.keys(ali_account_info).length) {
        const { id } = ali_account_info
        alipayAccountId = id
      } else {
        alipayAccountId = -1
      }

      this.list = this.list.map(item => {
        item.alipayAccountId = alipayAccountId

        if (!Object.keys(ali_account_info).length) {
          // 如果总部账号未开通的话
          item.alipayStatus = 1
          item.alipayIdcard = '未设置'
          item.alipayCustomerName = '未设置' // 银行户名
          item.alipayCardNo = '未设置' // 银行账户
        } else {
          // 如果总部账号已开通的话
          const { ali_platform_info } = item

          if (!Object.keys(ali_platform_info).length) {
            // 如果该门店账号未开通的
            item.alipayStatus = 2
            item.alipayIdcard = ali_account_info.pay_account.account_info.id_card
            item.alipayCustomerName = ali_account_info.pay_account.account_info.customer_name
            item.alipayCardNo = ali_account_info.pay_account.account_info.card_no
          } else {
            // 总部门店都已经开通
            const { pay_account: { account_info: { customer_name, card_no, id_card } }, is_used } = ali_platform_info

            if (is_used === 1) {
              // 使用门店配置
              item.alipayStatus = 3
              item.alipayIdcard = id_card
              item.alipayCustomerName = customer_name // 银行户名
              item.alipayCardNo = card_no // 银行账户
            } else {
              // 使用总部配置
              item.alipayStatus = 4
              item.alipayIdcard = ali_account_info.pay_account.account_info.id_card
              item.alipayCustomerName = ali_account_info.pay_account.account_info.customer_name
              item.alipayCardNo = ali_account_info.pay_account.account_info.card_no
            }
          }
        }
        return item
      })
    },

    getClientPhone () {
      http.request(this, api.client_phone_info, null, null, (res, err) => {
        if (!res || err) {
          return
        }
        this.clientPhone = res.phone
      })
    },
    success (r) {
      this.formItem.captcha_code = r
    },
    sendSMS () {
      if (!this.formItem.captcha_code) {
        this.$Message.error('请进行人机识别认证')
      } else {
        this.isWaitingForSMS = true
        this.timer = setInterval(() => {
          if (this.second === 0) {
            clearInterval(this.timer)
            this.isWaitingForSMS = false
            this.second = 60
          } else {
            this.second -= 1
          }
        }, 1000)
        let params = {
          captcha_code: this.formItem.captcha_code
        }
        http.request(this, api.sms, null, params, res => {
          if (res) {
            this.$Message.success('短信发送成功')
          }
        })
      }
    },

    saveBankCard (name) {
      // 保存账户
      if (this.isLoadig) {
        return
      }
      this.$refs[name].validate(valid => {
        util.log(this.formItem)
        if (valid) {
          let { bank_name, bank_province, bank_city } = this.formItem
          if (!bank_name) {
            this.$Message.info('请选择开户银行')
            return
          }
          if (!bank_province) {
            this.$Message.info('请选择开户银行所在省')
            return
          }
          if (!bank_city) {
            this.$Message.info('请选择开户银行所在县')
            return
          }
          this.formItem.phone_no = +this.formItem.phone_no
          let params = this.formItem
          this.isLoadig = true
          http.request(this, api.pay_accounts_create, null, params, res => {
            if (res) {
              this.isLoadig = false
              this.addAccount = false
              this.$Modal.info({
                title: '提示',
                content: '门店账户已更新成功，商户自动转账功能开通后将生效。',
                okText: '我已知悉'
              })
              this.getList()
            } else {
              this.isLoadig = false
            }
          })
        }
      })
    },

    ok () {
      if (this.add_branch_name.length > 12) {
        this.$Message.error('门店名称过长')
        return
      }

      if (!this.add_branch_name.trim()) {
        this.$Message.error('请输入门店名称')
        return
      }
      http.request(this, api.branch_create, null, { name: this.add_branch_name }, (res, err) => {
        if (!res || err) {
          return
        }
        this.add_branch_name = ''
        this.getList()
        this.add_model = false
        this.accountForm.branch_id = res.branch_id
        this.add_branch_name = ''
        // this.tip_model = true
        this.$Message.success('添加门店成功')
        dataCenter.updateStores(this)
      })
      this.getList()
    },

    cancelPass (num) {
      switch (num) {
        case 1:
          this.add_model = false
          break
        case 2:
          this.edit_model = false
          break
        case 3:
          this.delete_model = false
          break
        case 4:
          this.tip_model = false
          break
      }
    },

    /**
         * 修复账户类型
         */
    changeAccountType (type) {
      const status = this.bankParams.status

      if (status === 2) {
        // 当总部开通门店未开通情况下
        if (type === 2) {
          // 由总部切换为门店的时候
          this.setButtonName(5)
        } else {
          // 由分店切换为总部
          this.setButtonName(2)
        }
      } else if (status === 3 || status === 4) {
        // 当总部和门店都已经开通
        if (type === 1) {
          // 由分店切换为总部
          this.setButtonName(4)
        } else {
          // 由总部切换为分店
          this.setButtonName(3)
        }
      }

      const params = type === 1 ? null : { branch_id: this.bankParams.id }
      http.request(this, api.pay_accounts_info, null, params, res => {
        // if (res.id) {
        //     // 当有数据的时候更新数据
        // const { pay_account: { account_info: { customer_name, card_no } } } = res;
        // this.setBankData(customer_name, card_no);
        // } else {
        //     this.setBankData('未设置');
        // }
        if (res) {
          const payAccount = res.find(item => item.platform_type === 1)

          if (payAccount) {
            const { pay_account: { account_info: { customer_name, card_no } }, id } = payAccount
            this.setBankData(customer_name, card_no)

            this.$set(this.bankParams, type === 1 ? 'clientAccountId' : 'routeAccountId', id)
          } else {
            this.setBankData('未设置')
          }
        }
      })
    },

    setButtonName (flag, pos = false) {
      if (!pos) {
        this.$set(this.bankParams, 'prevName', this.getPrevName(flag, pos))
        this.$set(this.bankParams, 'nextName', this.getNextName(flag))
      } else {
        this.$set(this.alipayParams, 'prevName', this.getPrevName(flag))
        this.$set(this.alipayParams, 'nextName', this.getNextName(flag))
      }
    },

    setBankData (name, no) {
      if (!no) {
        no = name
      }
      this.$set(this.bankParams, 'customerName', name)
      this.$set(this.bankParams, 'cardNo', no)
    },

    /**
        * 编辑支付宝收款账号
        */
    editAlipayCard (item) {
      const { alipayStatus, alipayIdcard, alipayCustomerName, alipayCardNo, id, ali_platform_info, alipayAccountId } = item

      let alipayRouteAccountId
      if (!Object.keys(ali_platform_info).length) {
        alipayRouteAccountId = -1
      } else {
        alipayRouteAccountId = ali_platform_info.id
      }

      const prevName = this.getPrevName(alipayStatus)
      const nextName = this.getNextName(alipayStatus)

      this.alipayParams = {
        alipayStatus,
        alipayCustomerName,
        alipayIdcard,
        alipayCardNo,
        prevName,
        id, // 商户id
        alipayAccountId,
        nextName,
        account: alipayStatus !== 3 ? 1 : 2,
        isDisable: alipayStatus === 1,
        alipayRouteAccountId
      }

      if (this.alipayParams.account === 2) {
        this.changeAlipayAccountType(2)
      }

      this.alipayAccoundModal = true
    },

    /**
         * 编辑收款账户
         */
    editBankCard (item) {
      const { customerName, cardNo, status, id, clientAccountId, unionpay_account_info } = item

      let routeAccountId
      if (!Object.keys(unionpay_account_info).length) {
        routeAccountId = -1
      } else {
        routeAccountId = unionpay_account_info.id
      }

      const prevName = this.getPrevName(status, false)
      const nextName = this.getNextName(status)

      this.bankParams = {
        customerName,
        cardNo,
        account: status !== 3 ? 1 : 2,
        isDisable: status === 1,
        status,
        id,
        tip: status === 1 ? '请联系商户，通过资金中心开通功能' : '',
        prevName,
        nextName,
        clientAccountId,
        routeAccountId
      }

      this.accoundModal = true
    },

    getPrevName (status, pos = true) {
      if (status === 1) {
        return '确定'
      } else if (status === 2 || status === 4) {
        return '返回'
      } else if (status === 3) {
        // return '变更收款账户' 暂时屏蔽等银联开通
        if (!pos) {
          return ''
        }
        return '变更收款账户'
      } else if (status === 5) {
        if (!pos) {
          return ''
        }
        return '申请开通'
      }
    },

    getNextName (status) {
      if (status === 1) {
        return ''
      } else if (status === 2) {
        return ''
      } else if (status === 3 || status === 4) {
        return '确认切换'
      } else if (status === 5) {
        return ''
      }
    },

    openAccount () {
      this.accoundModal = false
    },

    cancel () {
      this.addAccount = false
      // this.resetForm('addBankForm');
    },

    getPayProvinces () {
      http.request(this, api.pay_provinces, null, null, res => {
        if (res) {
          this.provinces = res
        }
      })
    },
    getPayCountry (province, bank_city) {
      http.request(this, api.pay_country, null, { province }, res => {
        if (res) {
          this.formItem.bank_city = ''
          this.countrys = []
          this.countrys = res

          if (bank_city) {
            this.formItem.bank_city = bank_city
          }
        }
      })
    }
    // getPayBanks() {
    //     http.request(this, api.pay_banks, null, null, res => {
    //         if (res) {
    //             this.banks = res
    //         }
    //     })
    // }
  },
  watch: {
    introductionVisible (val) {
      if (!val) {
        this.isChangeAccountType = val
      }
    }

    // alipayAccoundModal(value) {
    //     if (!value) {
    //         this.alipayData = {};
    //     }
    // }
  },

  computed: {
    introductionVisible () {
      return this.enableRecharge.introductionVisible
    },
    isClient () {
      return this.$store.state.user.roleId === 100
    }
  },

  filters: {
    phoneNumber: function (input) {
      return input.slice(0, 3) + '****' + input.slice(7, 11)
    },
    statusFilter (status) {
      if (status === 2 || status === 4) {
        return '总部配置'
      } else if (status === 3) {
        return '门店配置'
      } else {
        return '未设置'
      }
    }
  },
  components: {
    captcha,
    rechargeIntroduction,
    enableRecharge,
    alipayRecharge,
    tooltipModal
  }
}
</script>
<style lang="less" scope>
@import '../../styles/common.less';
.no-data {
    background: #fff;
    padding: 50px 0;
    text-align: center;
}

.store {
    &-item {
        border: 1px solid #e9eaec;
        height: 214px;
        background-color: #fff;
        &:hover {
            box-shadow: 0 2px 8px 0 #d0d0d0;
        }
        &-left {
            height: 100%;
            color: #5b5b5b;
            border-right: 1px dashed #ccc;
            font-weight: 700;
            word-break: break-all;
        }
        &-center {
            font-size: 14px;
            color: #5b5b5b;
            padding-left: 25px;
            padding-top: 15px;
        }
        &-right {
            border-left: 1px dashed #ccc;
            // height: 146px;
            text-align: center;
            button {
                width: 80%;
                margin-bottom: 10px;
            }
            button:nth-child(1) {
                margin-top: 8px;
            }
        }
    }
}
.mb-min {
    margin-bottom: 6px !important;
}
</style>